package cn.wildfire.chat.app.extendsion.classes;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.wildfire.chat.app.extendsion.https.OkHttpRequest;
import cn.wildfire.chat.app.extendsion.https.ReqCallBack;
import cn.wildfire.chat.app.extendsion.https.ServerUrlClient;

/**
 * Create by HEKE, 2019/8/22 17:39
 * TODO 获取所有国家及其对应区号信息
 */
public class RegionFetcherRequest {

    private Context context;
    private RegionRet mRegionRet; // 请求国家区域结果对象

    public RegionFetcherRequest(Context context) {
        this.context = context;
        postRegionDatas();
    }

    /**
     * 获取区号数据
     */
    private void postRegionDatas() {
        OkHttpRequest.getNewInstance(context).requestAsyn(ServerUrlClient.REGION, OkHttpRequest.TYPE_POST_JSON, null, new ReqCallBack<Object>() {
            @Override
            public void onReqSuccess(Object result) {
                try {
                    String ret = result.toString();
                    if (ret != null) {
                        RegionRet regionRet = new Gson().fromJson(ret, RegionRet.class);
                        if (regionRet != null) {
                            regionRet.regionArrayList = new ArrayList<>();
                            JSONArray array = new JSONObject(ret).getJSONArray("result");
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.getJSONObject(i);
                                Region region = new Gson().fromJson(object.toString(), Region.class);
                                regionRet.regionArrayList.add(region);
                            }
                            mRegionRet = regionRet;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("Get Region", "Error : " + errorMsg);
            }
        }).request();
    }

    /**
     * 获取区号结果
     */
    public RegionRet getmRegionRet() {
        return mRegionRet;
    }

}
